import axios from "axios";
import UtilVar from "@/config/UtilVar";
import { getToken } from "@/utils/auth";
import { Message, Loading } from "element-ui";
import { saveAs } from "file-saver";

let baseUrl = UtilVar.baseUrl;
const CancelToken = axios.CancelToken;
export { baseUrl };
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 对应国际化资源文件后缀
axios.defaults.headers["Content-Language"] = "zh_CN";
// 创建axios实例
const service = axios.create({
	// axios中请求配置有baseURL选项，表示请求URL公共部分
	baseURL: baseUrl,
	// 超时
	timeout: 10000,
});

// 添加请求拦截器
service.interceptors.request.use(
	(config) => {
		// 是否需要设置 token
		const isToken = (config.headers || {}).isToken === false;
		// 是否需要防止数据重复提交
		const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
		if (getToken() && !isToken) {
			config.headers["Authorization"] = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
		}
		// get请求映射params参数
		if (config.method === "get" && config.params) {
			let url = config.url + "?" + tansParams(config.params);
			url = url.slice(0, -1);
			config.params = {};
			config.url = url;
		}
		if (config.method === "post" || config.method === "put") {
			const requestObj = {
				url: config.url,
				data:
					typeof config.data === "object"
						? JSON.stringify(config.data)
						: config.data,
				time: new Date().getTime(),
			};
		}

		return config;
	},
	(error) => {
		console.log(error);
		Promise.reject(error);
	}
);
/**
 * @响应拦截
 */
service.interceptors.response.use(
	(res) => {
		const code = res.data.code;
		// 获取信息
		const msg = res.data.msg;
		if (res.request.responseType === "blob") {
			return res.data;
		}
		if (code === 200 || code === 401) {
			return res.data;
		} else {
			Message({
				message: msg,
				type: "error",
				duration: 5 * 1000,
			});
			return Promise.reject(new Error(msg));
		}
	},
	(error) => {
		console.error(error);
		let err = {
			success: false,
			msg: "未知异常，请联系管理员！",
		};
		return Promise.reject(err);
	}
);
// 通用下载方法
let downloadLoadingInstance;
export function download(url, params, filename) {
	downloadLoadingInstance = Loading.service({
		text: "正在下载数据，请稍候",
		spinner: "el-icon-loading",
		background: "rgba(0, 0, 0, 0.7)",
	});
	return service
		.post(url, params, {
			transformRequest: [
				(params) => {
					return tansParams(params);
				},
			],
			headers: { "Content-Type": "application/x-www-form-urlencoded" },
			responseType: "blob",
		})
		.then(async (data) => {
			// const isLogin = await blobValidate(data)
			// if (isLogin) {
			const blob = new Blob([data]);
			saveAs(blob, filename);
			// } else {
			// 	const resText = await data.text()
			// 	const rspObj = JSON.parse(resText)
			// 	const errMsg =
			// 		errorCode[rspObj.code] || rspObj.msg || errorCode['default']
			// 	Message.error(errMsg)
			// }
			downloadLoadingInstance.close();
		})
		.catch((r) => {
			console.error(r);
			Message.error("下载文件出现错误，请联系管理员！");
			downloadLoadingInstance.close();
		});
}

export default service;

function tansParams(params) {
	let result = "";
	for (const propName of Object.keys(params)) {
		const value = params[propName];
		var part = encodeURIComponent(propName) + "=";
		if (value !== null && typeof value !== "undefined") {
			if (typeof value === "object") {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && typeof value[key] !== "undefined") {
						let params = propName + "[" + key + "]";
						var subPart = encodeURIComponent(params) + "=";
						result += subPart + encodeURIComponent(value[key]) + "&";
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&";
			}
		}
	}
	return result;
}
